package com.youxin.third.auth.config.interceptors;

import com.alibaba.fastjson.JSONObject;
import com.youxin.auth.client.utils.JwtTokenClientUtils;
import com.youxin.auth.utils.JwtUserInfo;
import com.youxin.base.BaseResultCode;
import com.youxin.base.TResult;
import com.youxin.context.BaseContextConstants;
import com.youxin.context.BaseContextHandler;
import com.youxin.utils.StrHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Optional;

/**
 * description: OAuthInterceptor <br>
 * date: 2020/3/8 11:28 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Component
public class OAuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtTokenClientUtils jwtTokenClientUtils;

    private static final Logger log = LoggerFactory.getLogger(OAuthInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {

            Cookie[] cookies = request.getCookies();
            String token =request.getParameter("token");
            if (cookies != null && cookies.length > 0) {
                Optional<Cookie> cookie =  Arrays.stream(cookies).filter(item -> item.getName().equals("token")).findFirst();
                token = cookie.map(Cookie::getValue).orElse(token);
            }

            if(StringUtils.isEmpty(token)){
                returnJson(response);
                return false;
            }
            JwtUserInfo userInfo = jwtTokenClientUtils.getUserInfo(token);
            if(userInfo == null){
                returnJson(response);
                return false;
            }
            String id = getHeader(request,BaseContextConstants.JWT_KEY_ID);
            BaseContextHandler.setUserNo(userInfo.getUserNo());
        } catch (Exception e) {
            log.warn("解析token信息时，发生异常. ", e);
        }
        return super.preHandle(request, response, handler);
    }

    private String getHeader(HttpServletRequest request, String name) {
        String value = request.getHeader(name);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        return StrHelper.decode(value);
    }


    private void returnJson(HttpServletResponse response){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        try {
            writer = response.getWriter();
            TResult result =TResult.build(BaseResultCode.COMMON_FAIL,"您无权限访问此操作");
            writer.print(JSONObject.toJSONString(result));
        } catch (IOException e){
            log.error("拉截器异常",e);
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }

}
